package com.common.library.util;

import java.util.ArrayList;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES加解密
 *
 * @author chengfu.bao
 */
public class AES {
    private static final String ENCODING_UTF8 = "utf-8";
    private static final String ALGORITHM_TYPE = "AES";
    private static final String CLPHER_TRANSFORMATION = "AES/ECB/PKCS5Padding";

    private static Cipher createCipher(int opmode, String key) {
        try {
            byte[] enCodeFormat = key.getBytes(ENCODING_UTF8);
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, ALGORITHM_TYPE);
            Cipher cipher = Cipher.getInstance(CLPHER_TRANSFORMATION);// 创建密码器
            cipher.init(opmode, secretKeySpec);// 初始化
            return cipher;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 加密
     *
     * @param content 需要加密的内容
     * @param key     加密密码
     * @return
     */
    public static byte[] encrypt(String content, String key) {
        if (Helper.isNotEmpty(content) && Helper.isNotEmpty(key)) {
            try {
                return encrypt(content.getBytes(ENCODING_UTF8), key);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 加密
     *
     * @param content 需要加密的内容
     * @param key     加密密码
     * @return
     */
    public static byte[] encrypt(byte[] content, String key) {
        if (Helper.isNotEmpty(content) && Helper.isNotEmpty(key)) {
            try {
                Cipher cipher = createCipher(Cipher.ENCRYPT_MODE, key);
                if (cipher != null) {
                    byte[] result = cipher.doFinal(content);
                    return result; // 加密
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 加密
     *
     * @param content   需要加密的内容
     * @param key       加密密码
     * @param blockSize 分块加密大小
     * @return
     */
    public static byte[] encrypt(String content, String key, int blockSize) {
        if (Helper.isNotEmpty(content) && Helper.isNotEmpty(key)) {
            try {
                return encrypt(content.getBytes(ENCODING_UTF8), key, blockSize);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    public static byte[] encryptWithIV(String content,String secretKey) throws Exception {
        try {
            String data = content;
            String key = secretKey;
            String iv = "1236547887654123";
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            int blockSize = cipher.getBlockSize();
            byte[] dataBytes = data.getBytes();
            int plaintextLength = dataBytes.length;
            if (plaintextLength % blockSize != 0) {
                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
            }
            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(plaintext);
            return encrypted;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }



    /**
     * 加密
     *
     * @param content   需要加密的内容
     * @param key       加密密码
     * @param blockSize 分块加密大小
     * @return
     */
    public static byte[] encrypt(byte[] content, String key, int blockSize) {
        if (Helper.isNotEmpty(content) && Helper.isNotEmpty(key)) {
            try {
                ArrayList<Byte> list = new ArrayList<Byte>();
                int size = content.length / blockSize;//Math.round(content.length * 1.0f / blockSize);
                if (size * blockSize < content.length) {
                    size++;
                }
                for (int i = 0; i < size; i++) {
                    int realSize = blockSize;
                    if (i == size - 1) {
                        realSize = content.length - i * blockSize;
                    }
                    byte[] curBytes = new byte[realSize];
                    System.arraycopy(content, i * blockSize, curBytes, 0, realSize);
                    byte[] encryptBytes = encrypt(curBytes, key);
                    if (encryptBytes != null) {
                        for (byte b : encryptBytes) {
                            list.add(b);
                        }
                    }
                }
                byte[] result = new byte[list.size()];
                for (int i = 0; i < list.size(); i++) {
                    result[i] = list.get(i).byteValue();
                }
                return result;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 解密
     *
     * @param content 待解密内容
     * @param key     解密密钥
     * @return
     */
    public static byte[] decrypt(byte[] content, String key) {
        if (Helper.isNotEmpty(content) && Helper.isNotEmpty(key)) {
            try {
                Cipher cipher = createCipher(Cipher.DECRYPT_MODE, key);
                if (cipher != null) {
                    byte[] result = cipher.doFinal(content);
                    return result; // 解密
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    @SuppressWarnings("unused")
    private static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    @SuppressWarnings("unused")
    private static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),
                    16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }
}
